from django.shortcuts import render,redirect
from web.forms.project import ProjectModelForm
from django.http import JsonResponse,HttpResponse
from web import models
from utils.tecent.cos import create_bucket
import time
from pypinyin import pinyin, Style

def chinese_to_pinyin(chinese_text):
    # 获取拼音列表，每个字对应一个拼音
    pinyin_list = pinyin(chinese_text, style=Style.NORMAL)
    # 将拼音列表拼接成字符串
    pinyin_str = ''.join([item[0] for item in pinyin_list])
    return pinyin_str
def project_list(request):
    if request.method == 'GET':
         # GET请求查看项目列表
        """
        1. 从数据库中获取两部分数据
            我创建的所有项目：已星标、未星标
            我参与的所有项目：已星标、未星标
        2. 提取已星标
            列表 = 循环 [我创建的所有项目] + [我参与的所有项目] 把已星标的数据提取
        
        得到三个列表：星标、创建、参与
        """
        project_dict = {'star': [], 'my': [], 'join': []}

        my_project_list = models.Project.objects.filter(creator=request.tracer.user)
        for row in my_project_list:
            if row.star:
                project_dict['star'].append({"value": row, 'type': 'my'})
            else:
                project_dict['my'].append(row)

        join_project_list = models.ProjectUser.objects.filter(user=request.tracer.user)
        for item in join_project_list:
            if item.star:
                project_dict['star'].append({"value": item.project, 'type': 'join'})
            else:
                project_dict['join'].append(item.project)

        form = ProjectModelForm(request)
        return render(request, 'project_list.html', {'form': form, 'project_dict': project_dict})

    form = ProjectModelForm(request,data=request.POST)
    if form.is_valid():
        project_name = form.cleaned_data['name']
        name = chinese_to_pinyin(project_name)
        #1.创建桶
        bucket = "{}-{}-{}-1339193718".format(name,request.tracer.user.mobile_phone, str(int(time.time())))
        region = 'ap-beijing'
        create_bucket(bucket, region)
        #把桶和区域写入数据库
        form.instance.bucket = bucket
        form.instance.region = region

        #验证通过
        form.instance.creator = request.tracer.user
        #2.创建项目
        instance=form.save()
        #3.为项目初始化问题类型
        issues_type_object_list = []
        for item in models.IssuesType.PROJECT_INIT_LIST:
            issues_type_object_list.append(models.IssuesType(project=instance, title=item))
        models.IssuesType.objects.bulk_create(issues_type_object_list)
        return JsonResponse({'status':True})
    return JsonResponse({'status': False, 'error': form.errors})

def project_star(request, project_type, project_id):
    """ 星标项目 """
    if project_type == 'my':
        models.Project.objects.filter(id=project_id, creator=request.tracer.user).update(star=True)
        return redirect('project_list')

    if project_type == 'join':
        models.ProjectUser.objects.filter(project_id=project_id, user=request.tracer.user).update(star=True)
        return redirect('project_list')

    return HttpResponse('请求错误')


def project_unstar(request, project_type, project_id):
    """ 取消星标 """
    if project_type == 'my':
        models.Project.objects.filter(id=project_id, creator=request.tracer.user).update(star=False)
        return redirect('project_list')

    if project_type == 'join':
        models.ProjectUser.objects.filter(project_id=project_id, user=request.tracer.user).update(star=False)
        return redirect('project_list')

    return HttpResponse('请求错误')